package com.wei.web.demo.util.limiter.repository;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class MemoryLimiterRepository implements LimiterRepository {
    private Map<String, ReentrantLock> resourceLock = new LinkedHashMap<>();
    private Map<String, String> resourceData = new LinkedHashMap<>();

    @Override
    public boolean lockResource(String resourceCode) {
        ReentrantLock data = resourceLock.get(resourceCode);
        if (data == null) {
            data = new ReentrantLock();
            resourceLock.put(resourceCode, data);
        }
        data.lock();
        return true;
    }

    @Override
    public boolean unlockResource(String resourceCode) {
        ReentrantLock data = resourceLock.get(resourceCode);
        if (data == null) {
            return true;
        }
        data.unlock();
        return true;
    }

    @Override
    public String getData(String resourceCode) {
        return resourceData.get(resourceCode);
    }

    @Override
    public void setData(String resourceCode, String data) {
        resourceData.put(resourceCode, data);
    }
}
